//
//  AppDelegate.m
//  wtshoppingcite
//
//  Created by TW on 14-10-14.
//  Copyright (c) 2014年 TW. All rights reserved.
//

#import "AppDelegate.h"
#import "MainViewController.h"
#import "LoginViewController.h"
#import "GlobalViewControllers.h"
#import "GexinSdk.h"
#import "RegisterHelper.h"
#import <AlipaySDK/AlipaySDK.h>
#import "MobClick.h"
#import "Macro.h"

#import "CustomGuidView.h"


#import <AlipaySDK/AlipaySDK.h>
#define kAppId           @"b3KbaFR7oi6HeV97WMvSpA"
#define kAppKey          @"GVdShj75Xg9AqynrvaTWN6"
#define kAppSecret       @"RfAWdKBmuF7ZE2i7SWGfA5"
#define UMENG_APPKEY     @"5523a527fd98c5be5f00083e"

@interface AppDelegate ()<GexinSdkDelegate,BMKGeneralDelegate,BMKLocationServiceDelegate>
{
    BMKLocationService *_locService;
    BMKMapManager *_mapManager;
    PPRevealSideViewController *revealSideViewController;

}

@end

@implementation AppDelegate


#pragma mark - Application Lifecycle

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    self.isLogin = NO;
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    
    [self initLoginViewControllerWithStoryBoardIdentifier];
    [[RegisterHelper shareHelper] setShopCarNumbers:[[NSMutableDictionary alloc] init]];
    
    // [1]:使用APPID/APPKEY/APPSECRENT创建个推实例
    [self startSdkWith:kAppId appKey:kAppKey appSecret:kAppSecret];
    
    // [2]:注册APNS
    [self registerRemoteNotification];
    
    [[UIApplication sharedApplication] cancelAllLocalNotifications];
    [UIApplication sharedApplication].keyWindow.backgroundColor = [UIColor whiteColor];
    
    NSDictionary * apsDict = [launchOptions objectForKey:@"UIApplicationLaunchOptionsRemoteNotificationKey"];
    NSString* badge = [apsDict objectForKey:@"badge"];
    [UIApplication sharedApplication].applicationIconBadgeNumber = badge.intValue;
    //当程序在关闭状态从通知中心进入时，在此存储推送信息
    if(application.applicationState == UIApplicationStateInactive)
    {
        [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
    }
    
    _mapManager = [[BMKMapManager alloc]init];
    BOOL ret = [_mapManager start:kPoiSearchAK generalDelegate:self];
    if (!ret) {
        NSLog(@"manager start failed!");
    }
    
    _locService = [[BMKLocationService alloc]init];
    _locService.delegate = self;
    [_locService startUserLocationService];
    //umeng
    [self umengTrack];
    //测试umeng
    Class cls = NSClassFromString(@"UMANUtil");
    SEL deviceIDSelector = @selector(openUDIDString);
    NSString *deviceID = nil;
    if(cls && [cls respondsToSelector:deviceIDSelector]){
        deviceID = [cls performSelector:deviceIDSelector];
    }
    NSData* jsonData = [NSJSONSerialization dataWithJSONObject:@{@"oid" : deviceID}
                                                       options:NSJSONWritingPrettyPrinted
                                                         error:nil];
    NSLog(@"%@", [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]);
    //向微信注册
    [WXApi registerApp:@"wx705c9dff9ae18d35"];
    return YES;
}



- (void)applicationWillResignActive:(UIApplication *)application {
    
    [BMKMapView willBackGround];
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    // [EXT] 切后台关闭SDK，让SDK第一时间断线，让个推先用APN推送
    [self stopSdk];
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    
}

-(void)applicationDidBecomeActive:(UIApplication *)application{
    
    // [EXT] 重新上线
    [self startSdkWith:_appID appKey:_appKey appSecret:_appSecret];
    [BMKMapView didForeGround];
    
}

//跳转支付宝钱包进行支付，需要将支付宝钱包的支付结果回传给SDK
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {
    
    if ([url.host isEqualToString:@"safepay"]) {
        [[AlipaySDK defaultService]
         processOrderWithPaymentResult:url
         standbyCallback:^(NSDictionary *resultDic) {
             NSLog(@"result = %@", resultDic);
         }];
    }
    
    //微信
    BOOL isSuc = [WXApi handleOpenURL:url delegate:self];
    NSLog(@"url %@ isSuc %d",url,isSuc == YES ? 1 : 0);
    return  isSuc;
    
    return YES;
}


- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
    NSLog(@"%@",userInfo);
    NSString* badge = [userInfo objectForKey:@"badge"];
    [UIApplication sharedApplication].applicationIconBadgeNumber = badge.integerValue;
    switch ([UIApplication sharedApplication].applicationState) {
        case UIApplicationStateInactive: //没有激活状态
        {
            NSLog(@"UIApplicationStateInactive");
            if (userInfo && [userInfo count] != 0) {
                [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
                
            }
        }
            break;
        case UIApplicationStateActive: //正在使用
        {
            NSLog(@"UIApplicationStateActive");
            TipLabel * tip = [[TipLabel alloc] init];
            NSString * alert = [[userInfo objectForKey:@"aps"] objectForKey:@"alert"];
            [tip showToastWithMessage:alert showTime:1.5f];
        }
            break;
        case UIApplicationStateBackground: //后台运行状态
        {
            NSLog(@"UIApplicationStateBackground");
            
        }
            break;
            
        default:
            break;
    }
    
}

- (void)applicationWillTerminate:(UIApplication *)application {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UMOnlineConfigDidFinishedNotification object:nil];
    
}


- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{
    return  [WXApi handleOpenURL:url delegate:self];
}

/** 推送*/
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken
{
    NSString *token = [[deviceToken description] stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"<>"]];
    [_deviceToken release];
    _deviceToken = [[token stringByReplacingOccurrencesOfString:@" " withString:@""] retain];
    NSLog(@"deviceToken:%@", _deviceToken);
    
    
    // [3]:向个推服务器注册deviceToken
    if (_gexinPusher) {
        [_gexinPusher registerDeviceToken:_deviceToken];
    }
    
    
}

#pragma mark - Methods
- (id)init{
    if(self = [super init]){
        scene = WXSceneTimeline;
    }
    return self;
}

//初始化主要视图
- (void)initMainViewControllerWithStoryBoardIdentifier:(NSString *)identifier type:(int)selectedIndex pushIn:(UIViewController*)vc
{
    
//    UIStoryboard *mainStoryBoard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
//    _mainTabVC = (MainViewController *)[mainStoryBoard instantiateViewControllerWithIdentifier:identifier];
//    _mainTabVC.selectedIndex = selectedIndex;
//    self.window.rootViewController = _mainTabVC;
    
    revealSideViewController = nil;
    UIStoryboard *mainStoryBoard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    _mainTabVC = (MainViewController *)[mainStoryBoard instantiateViewControllerWithIdentifier:identifier];
    _mainTabVC.selectedIndex = selectedIndex;
    if(!revealSideViewController){
        revealSideViewController = [[PPRevealSideViewController alloc] initWithRootViewController:_mainTabVC];
    }
    revealSideViewController.delegate = vc;
    revealSideViewController.bouncingOffset = 0;
    PPRevealSideInteractions inter = PPRevealSideInteractionNone;
    inter |= PPRevealSideInteractionContentView;
    revealSideViewController.tapInteractionsWhenOpened = inter;
    revealSideViewController.panInteractionsWhenOpened = inter;
    revealSideViewController.panInteractionsWhenClosed = inter;
    [vc presentViewController:revealSideViewController animated:NO completion:NULL];
    //    [self.window makeKeyAndVisible];

}


//初始化登录故事版
- (void)initLoginViewControllerWithStoryBoardIdentifier
{
    if([[ConfigData sharedInstance] isFirstLaunch]){
        [self enterIntoGuidView];
    }else{
        [self initLoginView];
    }
}

- (void)enterIntoGuidView
{
    CustomGuidView * guidView = [[CustomGuidView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    guidView.gType = GUIDE_TYPE_DEFAULT;
    NSArray * imgs = nil;
    if (IS_4_INCH_SCREEN) {
        imgs = @[@"commity.png",@"nearby_login",@"share_login",@"label.png"];
    }else{
        imgs =  @[@"commity_4s.png",@"nearby_4s.png",@"share_4s.png",@"label_4s.png"];
    }
    
    [guidView addBlock:^(CustomGuidView *gView) {
        [self initLoginView];
        
    }];
    [guidView initSubviewWithImages:imgs];
    [self.window addSubview:guidView];
}

-(void)initLoginView{
    
    UIStoryboard *mainStoryBoard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    _mainTabVC = (MainViewController *)[mainStoryBoard instantiateViewControllerWithIdentifier:@"MainViewController"];
    _mainTabVC.selectedIndex = 0;
    self.window.rootViewController = _mainTabVC;
}


//push到登录视图
- (void)pushLoginViewControllerWithStoryBoardIdentifier:(NSString *)identifier pushIn:(UIViewController*)vc
{
    UIStoryboard *loginStoryBoard = [UIStoryboard storyboardWithName:@"LoginStoryboard" bundle:nil];
    LoginViewController *loginVC = (LoginViewController *)[loginStoryBoard instantiateViewControllerWithIdentifier:identifier];
    UINavigationController *loginNac = [[UINavigationController alloc] initWithRootViewController:loginVC];
    [vc presentViewController:loginNac animated:YES completion:nil];
}


+ (AppDelegate *)sharedDelegate
{
    return (AppDelegate*)[[UIApplication sharedApplication] delegate];
}



#pragma mark UMeng

//友盟
- (void)umengTrack {
    //    [MobClick setCrashReportEnabled:NO]; // 如果不需要捕捉异常，注释掉此行
    [MobClick setLogEnabled:YES];  // 打开友盟sdk调试，注意Release发布时需要注释掉此行,减少io消耗
    [MobClick setAppVersion:XcodeAppVersion]; //参数为NSString * 类型,自定义app版本信息，如果不设置，默认从CFBundleVersion里取
    //
    [MobClick startWithAppkey:UMENG_APPKEY reportPolicy:(ReportPolicy) BATCH channelId:nil];
    //   reportPolicy为枚举类型,可以为 REALTIME, BATCH,SENDDAILY,SENDWIFIONLY几种
    //   channelId 为NSString * 类型，channelId 为nil或@""时,默认会被被当作@"App Store"渠道
    
    //      [MobClick checkUpdate];   //自动更新检查, 如果需要自定义更新请使用下面的方法,需要接收一个(NSDictionary *)appInfo的参数
    //    [MobClick checkUpdateWithDelegate:self selector:@selector(updateMethod:)];
    
    [MobClick updateOnlineConfig];  //在线参数配置
    //    1.6.8之前的初始化方法
    //    [MobClick setDelegate:self reportPolicy:REALTIME];  //建议使用新方法
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onlineConfigCallBack:) name:UMOnlineConfigDidFinishedNotification object:nil];
    
}

- (void)onlineConfigCallBack:(NSNotification *)note {
    
    NSLog(@"online config has fininshed and note = %@", note.userInfo);
}


- (void)startSdkWith:(NSString *)appID appKey:(NSString *)appKey appSecret:(NSString *)appSecret
{
    if (!_gexinPusher) {
        
        self.appID = appID;
        self.appKey = appKey;
        self.appSecret = appSecret;
        
        NSError *err = nil;
        _gexinPusher = [GexinSdk createSdkWithAppId:_appID
                                             appKey:_appKey
                                          appSecret:_appSecret
                                         appVersion:@"0.0.0"
                                           delegate:self
                                              error:&err];
    }
}


#pragma mark - APNS
- (void)registerRemoteNotification
{
#ifdef __IPHONE_8_0
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0) {
        
        UIUserNotificationSettings *uns = [UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeAlert|UIUserNotificationTypeBadge|UIUserNotificationTypeSound) categories:nil];
        [[UIApplication sharedApplication] registerForRemoteNotifications];
        [[UIApplication sharedApplication] registerUserNotificationSettings:uns];
    } else {
        UIRemoteNotificationType apn_type = (UIRemoteNotificationType)(UIRemoteNotificationTypeAlert|UIRemoteNotificationTypeSound|UIRemoteNotificationTypeBadge);
        [[UIApplication sharedApplication] registerForRemoteNotificationTypes:apn_type];
    }
#else
    UIRemoteNotificationType apn_type = (UIRemoteNotificationType)(UIRemoteNotificationTypeAlert|UIRemoteNotificationTypeSound|UIRemoteNotificationTypeBadge);
    [[UIApplication sharedApplication] registerForRemoteNotificationTypes:apn_type];
#endif
}



//获取uuid
-(NSString *)ppid
{
    UIDevice *myDevice = [UIDevice currentDevice];
    NSString *deviceUDID = [[myDevice identifierForVendor] UUIDString];
    return deviceUDID;
}



#pragma mark - GexinSdkDelegate
/**
 *  确保每次注册返回的clientId
 *
 *  @param clientId 和后台的唯一标示符
 */
- (void)GexinSdkDidRegisterClient:(NSString *)clientId
{
    
    // [4-EXT-1]: 个推SDK已注册
    _sdkStatus = SdkStatusStarted;
    self.clientId =[_gexinPusher clientId];
    
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject:_clientId forKey:@"CID"];
    [defaults synchronize];
    
    NSLog(@"#########%@",_clientId);
    
    
    //去掉服务器接口
    [self getBindGexin];
    
}

/**
 *  透传消息
 *
 *  @param [NSDate date]时间
 *  @param payloadMsg  内容
 {"content":"23952927550865439","msgType":"3000"}
 */
-(void)GexinSdkDidReceivePayload:(NSString *)payloadId fromApplication:(NSString *)appId
{
    NSData *payload = [_gexinPusher retrivePayloadById:payloadId];
    NSString *payloadMsg = nil;
    if (payload) {
        payloadMsg = [[NSString alloc] initWithBytes:payload.bytes
                                              length:payload.length
                                            encoding:NSUTF8StringEncoding];
        NSString *payLoadMsgStr = [[NSString alloc] initWithData:payload encoding:NSUTF8StringEncoding];
        NSLog(@"%@",payLoadMsgStr);
        NSDictionary* dic = [NSString jsonStringToObject:payLoadMsgStr];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"GetMessageFlag" object:nil userInfo:dic];
        
    }
    
}


-(void)getBindGexin{
    
    NSString *did = _clientId;
    NSString *pm = @"1";
    
    NSMutableDictionary *listDic = [NSMutableDictionary dictionary];
    SetValueForKey(listDic, did, @"did");
    SetValueForKey(listDic, pm, @"pm");
    
    [NetWorkService byRequestWithAPIPrefix:kBaseAppUrl
                              andAPISuffix:kGeTui
                             andHttpMethod:@"POST"
                             andParameters:listDic
                           andRequestCache:NO
                            andUseParamDic:YES
                       andPostDataEncoding:MKNKPostDataEncodingTypeJSON
                     andRequestFinishBlock:^(BYRequest *request, BYResponse *response) {
                         
                         if (response.isError) {
                             
                             DLog(@"error %@",response.errorMessage);
                             
                         }else{
                             
                             NSDictionary *responseDic = request.responseJSON;
                             DLog(@"成功数据:%@",responseDic);
                         }
                     }];
}



- (BOOL)checkSdkInstance
{
    if (!_gexinPusher) {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"错误" message:@"SDK未启动" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        [alertView show];
        [alertView release];
        return NO;
    }
    return YES;
}

- (void)setDeviceToken:(NSString *)aToken
{
    if (![self checkSdkInstance]) {
        return;
    }
    
    [_gexinPusher registerDeviceToken:aToken];
}

- (BOOL)setTags:(NSArray *)aTags error:(NSError **)error
{
    if (![self checkSdkInstance]) {
        return NO;
    }
    
    return [_gexinPusher setTags:aTags];
}

- (NSString *)sendMessage:(NSData *)body error:(NSError **)error {
    if (![self checkSdkInstance]) {
        return nil;
    }
    
    return [_gexinPusher sendMessage:body error:error];
}


- (void)initCustomerModel:(NSDictionary *)modelDic{
    self.isLogin = YES;
    
    if (self.customerModel == nil) {
        _customerModel = [[CustomerModel alloc]initWithCustomerInfo:modelDic];
    }
}



- (void)stopSdk
{
    if (_gexinPusher) {
        [_gexinPusher destroy];
        [_gexinPusher release];
        _gexinPusher = nil;
        
        _sdkStatus = SdkStatusStoped;
        
        [_clientId release];
        _clientId = nil;
        
    }
}

#pragma mark - BMKGeneralDelegate
- (void)onGetNetworkState:(int)iError
{
    if (0 == iError) {
        NSLog(@"联网成功");
    }
    else{
        NSLog(@"onGetNetworkState %d",iError);
    }
    
}

- (void)onGetPermissionState:(int)iError
{
    if (0 == iError) {
        NSLog(@"授权成功");
    }
    else {
        NSLog(@"onGetPermissionState %d",iError);
    }
}



#pragma mark - BMKLocationServiceDelegate
/**
 *用户位置更新后，会调用此函数
 *@param userLocation 新的用户位置
 */
- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation
{
    NSLog(@"didUpdateUserLocation lat %f,long %f",userLocation.location.coordinate.latitude,userLocation.location.coordinate.longitude);
    self.userlocation = userLocation;
    
    
    if(self.userlocation != nil){
        [_locService stopUserLocationService];
    }
    
    
    //------------------位置反编码---5.0之后使用-----------------
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    [geocoder reverseGeocodeLocation:userLocation.location
                   completionHandler:^(NSArray *placemarks, NSError *error){
                       
                       [self analyzePlaceMarks:placemarks];
                   }];

    
}


- (void)analyzePlaceMarks:(NSArray *)placemarks
{
    for (CLPlacemark *place in placemarks) {
        NSLog(@"name,%@",place.name);
        // 位置名
//                NSLog(@"thoroughfare,%@",place.thoroughfare);       // 街道
//                NSLog(@"subThoroughfare,%@",place.subThoroughfare); // 子街道
//                NSLog(@"locality,%@",place.locality);               // 市
//                NSLog(@"subLocality,%@",place.subLocality);         // 区
//                NSLog(@"country,%@",place.country);
//                NSLog(@"administrativeArea,%@",place.administrativeArea);
//
        NSString *locationStr = [NSString stringWithFormat:@"%@,%@",place.administrativeArea,place.locality];
        [RegisterHelper shareHelper].location = locationStr;
        
        NSLog(@"locationStr:%@",locationStr);
    }
    
}

#pragma mark - Weixin

-(void) onReq:(BaseReq*)req
{
    if([req isKindOfClass:[GetMessageFromWXReq class]])
    {
        // 微信请求App提供内容， 需要app提供内容后使用sendRsp返回
        NSString *strTitle = [NSString stringWithFormat:@"微信请求App提供内容"];
        NSString *strMsg = @"微信请求App提供内容，App要调用sendResp:GetMessageFromWXResp返回给微信";
        
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:strTitle message:strMsg delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        alert.tag = 1000;
        [alert show];
        [alert release];
    }
    else if([req isKindOfClass:[ShowMessageFromWXReq class]])
    {
        ShowMessageFromWXReq* temp = (ShowMessageFromWXReq*)req;
        WXMediaMessage *msg = temp.message;
        
        //显示微信传过来的内容
        WXAppExtendObject *obj = msg.mediaObject;
        
        NSString *strTitle = [NSString stringWithFormat:@"微信请求App显示内容"];
        NSString *strMsg = [NSString stringWithFormat:@"标题：%@ \n内容：%@ \n附带信息：%@ \n缩略图:%u bytes\n\n", msg.title, msg.description, obj.extInfo, msg.thumbData.length];
        
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:strTitle message:strMsg delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alert show];
        [alert release];
    }
    else if([req isKindOfClass:[LaunchFromWXReq class]])
    {
        //从微信启动App
        NSString *strTitle = [NSString stringWithFormat:@"从微信启动"];
        NSString *strMsg = @"这是从微信启动的消息";
        
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:strTitle message:strMsg delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alert show];
        [alert release];
    }
}

-(void) onResp:(BaseResp*)resp
{
    if([resp isKindOfClass:[SendMessageToWXResp class]])
    {
        NSString *strTitle = [NSString stringWithFormat:@"发送媒体消息结果"];
        NSString *strMsg = [NSString stringWithFormat:@"errcode:%d", resp.errCode];
        
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:strTitle message:strMsg delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alert show];
        [alert release];
    }
}



@end
